<?php
  
  function getComments($url) { 
    $query = "SELECT id FROM WebPage WHERE url = '" . $url . "'";
    $result = mysql_query($query);
    
    $return_val = array();

   if (mysql_num_rows($result) > 0) {
      $result_row = mysql_fetch_assoc($result);
      $return_string = "<chatroomjid>room_" . $result_row['id'] 
                     . "</chatroomjid>\n";
      $query = "SELECT Comment.*,User.name,Rating.total_rating "
             . "FROM (Comment "
             . "      JOIN User ON Comment.user_id = User.id "
             . "      LEFT JOIN (SELECT comment_id, "
             . "      SUM(rating) as total_rating "
             . "      FROM CommentRating GROUP BY comment_id) as Rating "
             . "      ON Rating.comment_id=Comment.id) "
             . " WHERE Comment.webpage_id = " . $result_row['id'] 
             . " ORDER BY id";
      $result = mysql_query($query);
      
      $return_string .= "<resultno>" . mysql_num_rows($result) 
                      . "</resultno>\n";

      $return_string .= "<comments>\n";
      while ($result_row = mysql_fetch_assoc($result)) {
        $return_string .= "<comment id=\"comment_" . $result_row['id'] . "\""; 
        if ($result_row['parent_id'] != null) {
          $return_string .= " parentid=\"comment_" 
                          . strval($result_row['parent_id']) . "\"";
        }
        $return_string .= ">\n";
        if ($result_row['total_rating'] == null) {
          $result_row['total_rating'] = 0;
        }
        $return_string .= "<rating>" . $result_row['total_rating']
                        . "</rating>";
        $return_string .= "<webpageid>" . strval($result_row['web_page_id'])
                        . "</webpageid>\n";
        $return_string .= "<username>" . strval($result_row['name'])
                        . "</username>\n";
        $return_string .= "<timestamp>" . strval($result_row['timestamp'])
                        . "</timestamp>\n";
        $return_string .= "<text>" . htmlentities($result_row['text']) . "</text>\n";
        $return_string .= "</comment>\n";
      }
      $return_string .="</comments>\n";
    } else {
      $page_id = registerPage($url);
      $return_string = "<chatroomjid>room_$page_id</chatroomjid>\n";
      $return_string .= "<resultno>0</resultno>";
    }
    return $return_string;
  }

?>
